<?php
namespace frontend\controllers;

use common\models\Imitation;
use common\models\UploadForm;
use common\models\User;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\data\Pagination;
use yii\db\Exception;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\Images;
use common\models\Type;
use yii\web\UploadedFile;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post','get'],
                ],
            ],
        ];
    }

    /*
     * 保存评论
     */
    public function actionComment(){
        $model = new UploadForm();
        $imitation = new Imitation();
        $imitation->image_id = Yii::$app->request->post("img_id");
        $imitation->user_id = Yii::$app->request->post("user_id");
        $imitation->create_time = time();
        $imitation->content = Yii::$app->request->post("content");

        $model->upImage($model);
        $imitation->info = ($model->file->size / 1024 / 1024) . 'MB';
        $imitation->url = 'assets\upload\\' . $model->dir . '\\' . $model->imgname . '.' . $model->file->extension;
        if ($imitation->validate()){
            try{
                $imitation->save();
                return $this->redirect(['site/info','id'=>$imitation->image_id ]);
            }catch (Exception $e){
                throw new \yii\web\UnauthorizedHttpException('天，失败了');
            }

        }
        Yii::$app->getSession()->setFlash('error', '没搞定啊，怎么办！');
        return $this->redirect(['site/info','id'=>$imitation->image_id ]);

    }

    /*
     * 分类
     */
    public function actionImages(){
        $type = Yii::$app->request->get('id');
        $images = Images::find()->where(['type'=>$type])->orderBy(['create_time'=>SORT_DESC])->asArray()->all();
//        echo "<pre>"; print_r($images); exit();
       return $this->render('images',['images'=>$images]);
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
         $model = Images::find()->orderBy(['create_time'=>SORT_DESC]);
//        echo '<pre>'; echo print_r($_SERVER);exit;
//            // 得到文章的总数（但是还没有从数据库取数据）
//           $count = $model->count();
//            // 使用总数来创建一个分页对象
//            $pagination = new Pagination(['totalCount' => $count,'pageSize'=>5]);
//
//            // 使用分页对象来填充 limit 子句并取得文章数据
//            $articles = $model->offset($pagination->offset)
//            ->limit($pagination->limit)
//            ->all();


           $type = Type::find()->orderBy(['id'=>SORT_DESC])->where('isdisplay=1')->orderBy(['type_sort'=>SORT_ASC])
               ->offset(0)->limit(3)->asArray()->all();
           foreach ($type as $k=>$v){
                $images[] = Images::find()->where('type=:type',[':type'=>$v['id']])
                    ->orderBy(['id'=>SORT_DESC])->offset(0)->limit(6)->asArray()->all();
           }
           $shuxing = [
               ['effect-sadie','img02'],
               ['effect-oscar','img08'],
               ['effect-marley','img09'],
               ['effect-roxy','img03'],
               ['effect-chico','img15'],
               ['effect-lily','img01'],
           ];
//echo '<pre>'; echo print_r($images);exit;

        return $this->render('index',['type'=>$type,'images'=>$images,'shuxing'=>$shuxing]);
    }

    /*
     * 详情
     */
    public function actionInfo($id){
//         $id =  Yii::$app->request->get('id');
         $model = Images::findOne($id);
         $imguser = Images::find()->where(['user_id'=>$model->user_id])->orderBy(['create_time'=>SORT_DESC])->asArray()->all();
         $uf = new UploadForm();
         $commentdata = Imitation::find()->where(['image_id'=>$model->id])->orderBy(['create_time'=>SORT_DESC])->asArray()->all();


        $shuxing = [
            'effect-sadie',
            'effect-oscar',
            'effect-marley',
            'effect-roxy',
            'effect-chico',
            'effect-lily',
        ];
        $sx = 0;
        $count = count($shuxing);
         foreach ($imguser as $k=>$v){
             $imguser[$k]['shuxing'] = $shuxing[$sx++];
             if ($sx >= $count)
                 $sx = 0;
         }
         foreach ($commentdata as $k=>$v){
             $user_info = User::findOne($v['user_id']);
             $commentdata[$k]['user_info'] = $user_info;
         }


//         echo '<pre>'; echo print_r($imguser);exit;
         return $this->render('info',['model'=>$model,'imguser'=>$imguser,'uf'=>$uf,'cd'=>$commentdata,'id'=>$id]);
    }


    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->renderPartial('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }

            }
        }

        return $this->renderPartial('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}
